<template>
  <div class="sidebar" :class="{ collapsed: isCollapsed, animated: isAnimated }" ref="sidebarRef"
    :style="{ width: sidebarWidth + 'px' }">
    <button @click="$emit('toggle')">≡</button>
    <el-tree ref="treeRef" v-show="!isCollapsed" :load="loadNode" :data="treeStore.baseTree" :props="defaultProps"
      @node-click="handleNodeClick">
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span v-html="highlightText(node.label)"></span>
        </span>
      </template>
    </el-tree>
    <div class="resizer" @mousedown="startResize"></div>
  </div>
  <ProjectDetailsModal v-model:visible="projectModalVisible" :projectData="selectedProject"
    :projectId="selectedProjectId" />
</template>

<script setup>
import { ref, watch, nextTick, onMounted } from 'vue';
import { useTreeStore } from '@/stores/treeStore';
import ProjectDetailsModal from '@/components/ProjectDetailsModal.vue';


const props = defineProps({
  isCollapsed: Boolean
});

const emit = defineEmits(['toggle', 'open']);

const treeStore = useTreeStore();

const sidebarWidth = ref(250);
const minWidth = 200;
const projectModalVisible = ref(false);
const selectedProject = ref({});
const selectedProjectId = ref(null);

const activeNode = ref(null);

const startResize = (e) => {
  e.preventDefault();
  window.addEventListener('mousemove', resize);
  window.addEventListener('mouseup', stopResize);
};

const resize = (e) => {
  const newWidth = Math.max(minWidth, e.clientX);
  sidebarWidth.value = newWidth;
};

const stopResize = () => {
  window.removeEventListener('mousemove', resize);
  window.removeEventListener('mouseup', stopResize);
};

const isAnimated = ref(false);

watch(() => props.isCollapsed, async () => {
  isAnimated.value = true;
  await nextTick();
  setTimeout(() => {
    isAnimated.value = false;
  }, 300);
});
const treeRef = ref(null);
watch(() => treeStore.baseTree, (newVal) => {
  if (newVal && newVal.length > 0) {

    // 使用 nextTick 确保 DOM 更新后再展开
    nextTick(() => {
      if (treeStore.isSearch && treeStore.baseTree) {
        emit('open')
      }
      Object.values(treeRef.value.store.nodesMap).forEach((v) => {
        if (treeStore.isSearch) {
          v.expand()
          return
        }
        if (!v.data.hasOwnProperty('isDq')) {
          v.expand()
        }
      })
      if(treeStore.searchParam.hasOwnProperty('proname')){
        window.showxzqByAttribute("区", "沈阳市", [treeStore.baseTree[0]['children'][0]['label']], true, null);
      }
      // if (typeof treeStore.baseTree[0]['children'][0]['label'] === 'string') {
      //   console.log(treeStore.baseTree[0]['children'][0]['label'])
      // }
    });
  }
}, { deep: true });

onMounted(() => {
  // treeStore.loadTreeData();
});

const loadNode = async (node, resolve) => {
  if (node.level === 0) {
    resolve(treeStore.baseTree);
  } else {
    const children = await treeStore.loadNodeChildren(node.data);
    resolve(children);
  }
};

const customNodeClass = (data, node) => {
  if (selectedProjectId.value != null && data.proid == selectedProjectId.value) {
    return 'activie-tree-node'
  }
  return null
}
const highlightText = (text) => {
  if (treeStore.searchParam && treeStore.searchParam.hasOwnProperty('proname')) {
    return text.replaceAll(treeStore.searchParam.proname, `<span class="highlight">${treeStore.searchParam.proname}</span>`)
  }
  return text
}

const defaultProps = {
  children: 'children',
  label: 'label',
  class: customNodeClass
};

const handleNodeClick = async (data) => {
  if (!data.children || data.children.length === 0) {
    activeNode.value = data.id;
    projectModalVisible.value = true;
    selectedProject.value = data.appendData;
    selectedProjectId.value = data.proid;


  }
};
</script>
<style>
.admin-mode .sidebar {
  top: 113px !important;
  height: calc(100vh - 113px) !important;
}
</style>
<style scoped>
.sidebar {
  height: calc(100vh - 60px);
  background-color: #f0f0f0;
  transition: none;
  overflow: hidden;
  position: fixed;
  top: 60px;
  left: 0;
  display: flex;
  flex-direction: column;
  z-index: 100;

  opacity: 0.8;

}



.sidebar.animated {
  transition: width 0.3s ease;
}

.sidebar.collapsed {
  width: 50px !important;
}

.sidebar ul {
  list-style-type: none;
  padding: 20px;
  flex-grow: 1;
  width: 100%;
}

.sidebar li {
  margin-bottom: 10px;
  white-space: nowrap;
}

button {
  width: 100%;
  padding: 10px;
  background-color: var(--el-color-primary);
  color: white;
  border: none;
  cursor: pointer;
  flex-shrink: 0;
}

.resizer {
  width: 5px;
  height: 100%;
  background: rgba(0, 0, 0, 0.1);
  position: absolute;
  right: 0;
  top: 0;
  cursor: col-resize;
}
</style>
<style>
.activie-tree-node {
  background-color: var(--el-color-primary);
  color: white;
}

.el-tree-node {
  color: black;
}

.highlight {
  color: red;
}
</style>
